<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\common\model\users;

use app\common\model\base\A3Mall;
use app\common\model\system\Setting;
use think\facade\Db;

class AccountLevelLimit extends A3Mall{

    protected $name = "users_account_level_limit";

    protected $type = [
        "user_id"=>"integer",
        "issue_level"=>"integer",
        "accept_level"=>"integer",
        "same_day_date"=>"string",
        "same_day_issue_num"=>"integer",
        "same_day_issue_amount"=>"float",
        "same_day_accept_num"=>"integer",
        "same_day_accept_amount"=>"float",
        "issue_count"=>"integer",
        "issue_amount"=>"float",
        "accept_count"=>"integer",
        "accept_amount"=>"float",
        "create_time"=>"integer",
        "update_time"=>"integer",
    ];

    const BUY_LEVEL_TYPE = [
        'issue'     => ['issue_level','buyIssueLevel'],
        'accept'    => ['accept_level','buyAcceptLevel'],
    ];


    /**
     * 插入默认值
     * @param $userId
     */
    public function insertDefault($userId) {
        // 获取等级
        $insertData = [
            'user_id'   => $userId,
            'same_day_date' => date('Y-m-d',time()),
            'same_day_accept_num'   => 0,
            'same_day_accept_num'   => 0,
            'create_time'  => time(),
        ];
        $insertData['update_time'] = $insertData['create_time'];
        $insertData = array_merge($insertData,[
            'update_time'  => $insertData['create_time'],
            'issue_level'  => $this->getIssueLevelDetails(null,0)['level_id'],
            'accept_level'  => $this->getAcceptLevelDetails(null,0)['level_id'],
        ]);
        return $this->insert($insertData);
    }

    /**
     * 通过用户ID获取当前等级信息
     * @param $userId
     * @return array|null|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function findByUserId($userId) {
        if(!$result = $this->findOne(['user_id'=>$userId])) {
            return null;
        }
        return $result;
    }


    /**
     * 获取剩余次数
     * @param $details 详情
     * @param null $date 日期
     */
    public function getIssueRemainTimes($details,$date = null) {
        $date = is_null($date)?date('Y-m-d'):$date;
        $date = is_integer($date)?date('Y-m-d',$date):$date;
        $userTimes = $details['same_day_date'] == $date?$details['same_day_issue_num']:0;
        return $details['issue-limits'] - $userTimes;
    }

    /**
     * 获取验证
     * @param $details 详情
     */
    public function getIssueVerify($details) {
        return substr(md5($details['same_day_date'] . $details['same_day_issue_num']),3,10);
    }


    /**
     * 获取接单价格范围
     * @param $details
     * @return array
     */
    public function getAcceptPriceRange($details){
        return [0,$details['accept-limits']];
    }


    /**
     * 发布统计
     * @param $findDetails 记录详情
     * @param $jobId
     * @param $amount
     * @param $date
     */
    public function issue($findDetails,$amount,$date) {
        $where = [
            'user_id'   => $findDetails['user_id'],
            'same_day_date' => $findDetails['same_day_date'],
            'same_day_issue_num'    => $findDetails['same_day_issue_num'],
        ];
        $date =  date('Y-m-d',is_string($date)?strtotime($date):$date);
        $update = [
            'issue_count'   => Db::raw('issue_count + 1'),
            'issue_amount'  =>  Db::raw('issue_amount + ' . $amount),
            'update_time'    => time(),
        ];

        if($findDetails['same_day_date'] != $date) {
            $update['same_day_date'] = $date;
            $update['same_day_issue_num'] = 1;
            $update['same_day_issue_amount'] = $amount;
            $update['same_day_accept_num'] = $update['same_day_accept_amount'] = 0;
        } else {
            $update['same_day_issue_num'] =  Db::raw('same_day_issue_num + 1');
            $update['same_day_issue_amount'] =  Db::raw('same_day_issue_amount + ' . $amount);
        }
        if(!$this->where($where)->update($update)) {
            throw new \Exception('数据发生变化，请刷新重试');
        }
        return true;
    }

    /**
     * 接任务统计
     * @param $findDetails 记录详情
     * @param $jobId
     * @param $amount
     * @param $date
     */
    public function accept($findDetails,$amount,$date) {
        $where = [
            'user_id'   => $findDetails['user_id'],
            'same_day_date' => $findDetails['same_day_date'],
            'same_day_accept_num'    => $findDetails['same_day_accept_num'],
        ];
        $date =  date('Y-m-d',$date);
        $update = [
            'accept_count'   => Db::raw('accept_count + 1'),
            'accept_amount'  =>  Db::raw('accept_amount + ' . $amount),
            'update_time'    => time(),
        ];

        if($findDetails['same_day_date'] != $date) {
            $update['same_day_date'] = $date;
            $update['same_day_accept_num'] = 1;
            $update['same_day_accept_amount'] = $amount;
            $update['same_day_issue_num'] = $update['same_day_issue_amount'] = 0;
        } else {
            $update['same_day_accept_num'] =  Db::raw('same_day_accept_num + 1');
            $update['same_day_accept_amount'] =  Db::raw('same_day_accept_amount + ' . $amount);
        }
        if(!$this->where($where)->update($update)) {
            throw new \Exception('数据发生变化，请刷新重试');
        }
        return true;
    }


    /**
     * 获取发布等级信息
     * @param null $issueLevelId
     * @param null $rechargeAmount
     * @throws \Exception
     */
    public function getIssueLevelDetails($issueLevelId=null,$rechargeAmount = null)
    {
        return $this->getLevelList($issueLevelId,$rechargeAmount,'issue_level','发布');
    }

    /**
     * 获取接单等级信息
     * @param null $acceptLevelId
     * @param null $rechargeAmount
     * @throws \Exception
     */
    public function getAcceptLevelDetails($acceptLevelId=null,$rechargeAmount = null)
    {
        return $this->getLevelList($acceptLevelId,$rechargeAmount,'accept_level','接单');
    }


    public function buy($details,$walletDetails,$buyLevel,$amount,$buyType) {
        $typeDetails = static::BUY_LEVEL_TYPE[$buyType];
        if(!$this->where([
            'user_id'   => $details['user_id'],
            $typeDetails[0] => $details[$typeDetails[0]],
        ])->update([
            $typeDetails[0] => $buyLevel,
            'update_time'   => time()
        ])) {
            throw new \Exception('数据发生变化，请刷新重试');
        }

        // 添加消耗记录
        (new WalletDetail())->recordAddToWallet($walletDetails,bcsub(0,$amount,2),$typeDetails[1],[]);

        return true;
    }

    /**
     * 获取等级信息
     * @param null $issueLevelId
     * @param null $rechargeAmount
     * @param $field
     * @param $fieldname
     * @throws \Exception
     */
    private function getLevelList($levelId = null,$rechargeAmount = null,$field,$fieldname)
    {
        if(!$list = (new Setting())->getConfigData($field)) {
            throw new \Exception($fieldname . '等级不存在');
        }
        $sortIds = array_map(function ($value){
            return $value['amount'];
        },$list);
        array_multisort($sortIds,SORT_ASC,$list);
        $result = $list;
        if(!is_null($levelId)) {  // 返回等级对应的详情
            $list = array_combine(array_column($list,'level_id'),$list);
//            print_r($list);
//            echo $levelId;exit;
            if(!array_key_exists($levelId,$list)) {
                throw new \Exception($fieldname . '等级ID不存在');
            }
            $result = $list[$levelId];
        } else if(!is_null($rechargeAmount)) { // 返回金额对应的详情
            $result = $list[0];
            foreach($list as $value) {
                if($value['amount'] > $rechargeAmount) {
                    break;
                }
                $result = $value;
            }
        }

        // 返回结果
        return $result;
    }

    /**
     * 查找单条记录
     * @param $where
     * @return array|null|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function findOne($where) {
        if(!$find = $this->where($where)->find()) {
            return null;
        }
        $find = $find->toArray();
        $issueDetails = $this->getIssueLevelDetails($find['issue_level']);
        foreach($issueDetails as $key=>$val) {
            if($key == 'level_id') {
                continue;
            }
            $find['issue-' . $key] = $val;
        }
        $acceptDetails = $this->getAcceptLevelDetails($find['accept_level']);
        foreach($acceptDetails as $key=>$val) {
            if($key == 'level_id') {
                continue;
            }
            $find['accept-' . $key] = $val;
        }
        // 返回详情
        return $find;
    }

   /* public function getTimeAttr($value){
        return date("Y-m-d H:i:s",$value);
    }*/

}
